<?php

namespace app\company\controller;

use app\admin\model\money\Change;
use app\admin\model\month\Salary;
use app\admin\model\product\Order;
use app\admin\model\profile\Cost;
use app\admin\model\user\Finance;
use app\admin\model\user\Sign;
use app\admin\model\Withdrawal;
use app\common\controller\Api;
use app\common\controller\CompanyApi;
use app\common\model\Config;
use think\Db;
use think\Request;


class Withdraw extends CompanyApi
{
    private static $model;
    protected $noNeedRight = '*';


    public function __construct()
    {
        parent::__construct();
        self::$model = new Withdrawal();
    }

    /**
     * 提现记录
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $pageSize = input('page_size', 15);
        $month = date('Y-m', time());
        $date = $this->request->post('date', $month);
        $start = strtotime($date);
        $userId = $this->auth->id;

        $where = [
            'user_id' => $userId,
            'createtime' => ['>=', $start]
        ];
        $lists = self::$model->field('id,order_num,money,createtime,status')->where($where)->order('createtime desc')->paginate($pageSize);

        if ($lists) {
            foreach ($lists as $val) {
                $val->createtime = date('Y年m月d日 H:i', $val->createtime);
            }
        }

        $this->success('提现记录', $lists);
    }

    /**
     * 余额提现
     */
    public function create()
    {
        $type = $this->request->post('type', 1);
        if (!in_array($type, [1, 2, 3])) {
            $this->error('参数错误！');
        }
        $userId = $this->auth->id;
        $user = \app\admin\model\department\User::find($userId);
        switch ($type) {
            case 1:
                $signConfig = sign_config($userId);
                $signConfig1 = array_slice($signConfig, 0, 2);
                $signConfig2 = array_slice($signConfig, 2, 2);
                $month = strtotime(date('Y-m-01 00:00:00', strtotime('today')));
                $days = (int)date('d', time());
                $num = 0;
//                for ($i = 0; $i < $days; $i++) {
//                    $start = $month + $i * 24 * 60 * 60;
//                    $end = $start + 24 * 60 * 60;
//                    $where = [
//                        'createtime' => [['>=', $start], ['<', $end]],
//                        'user_id' => $userId,
//                    ];
//
//                    $number = Sign::where($where)->count();
//                    if ($number >= 4) {
//                        $num += 1;
//                    }
//                }
                for ($i = 0; $i < $days; $i++) {
                    $date = date('Y-m-d', $month + $i * 86400);
                    $num1 = $this->getNum($signConfig1, $userId, $date);
                    $num += $num1;

                    $num2 = $this->getNum($signConfig2, $userId, $date);
                    $num += $num2;
                }

                $min_days = config('site.min_wd_days');
                if ($num < $min_days * 2) {
                    $this->error('当前不可提现！');
                }

                $wdinfo = Withdrawal::where('user_id', $userId)->where('status', '>=', 0)->where('type', 1)->where('createtime', '>=', $month)->find();
                if ($wdinfo) {
                    $this->error('本月已提现！');
                }

                // 上月
                $last_time = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
                $pcInfo = Cost::where('user_id', $userId)->where('date', $last_time)->find();
                if ($pcInfo && $pcInfo->status != 5) {
                    $this->error('上月支出尚未支付！');
                }

                // 本月
                $currrent_time = strtotime(date('Y-m-01 00:00:00', strtotime('today')));

                // 本月13号
                $currrent13_time = $currrent_time + 13 * 24 * 60 * 60;

                // 上月提成
                $money = Order::where('department_user_id', $userId)
                    ->where('status', 20)
                    ->where('pay_time', '>=', $last_time)
                    ->where('pay_time', '<', $currrent_time)
                    ->where('finish_time', '>=', $last_time)
                    ->where('finish_time', '<', $currrent13_time)
                    ->sum('total');
                // 上月底薪
                $last_salary = Salary::where('user_id', $userId)
                    ->where('datetime', $last_time)
                    ->value('salary');
                // 上月收益
                $last_profile = 0.00;
                if ($pcInfo) {
                    $last_profile = $pcInfo->profile_total;
                }
                // 上月工资
                $money = round(($money + $last_salary + $last_profile), 2);

                if ($user->is_leave == 1) {
                    // 已离职
                    // 本月提成
                    $current_money = Order::where('department_user_id', $userId)
                        ->where('status', 20)
                        ->where('pay_time', '>=', $currrent_time)
                        ->sum('profile');
                    // 本月底薪
                    $current_salary = Salary::where('user_id', $userId)
                        ->where('datetime', $currrent_time)
                        ->value('salary');
                    // 本月收益
                    $current_profile = Cost::where('user_id', $userId)
                        ->where('date', $currrent_time)
                        ->value('profile_total');
                    // 本月工资
                    $current_money = round(($current_money + $current_salary + $current_profile), 2);
                    // 总工资
                    $money = round(($money + $current_money), 2);
                }

                if ($money <= 0) {
                    $this->error('无可提现金额！');
                }

                break;
            case 2:
                if ($user->has_year_bonus <= 0) {
                    $this->error('非法操作！');
                }

                if ($user->is_unfreeze_year_bonus == 0) {
                    $this->error('尚未解冻，不可提现！');
                }

                $money = input('money');
                if (!$money || $money <= 0) {
                    $this->error('必须输入正确提现金额！');
                }

                if ($user->has_year_bonus < $money) {
                    $this->error('余额不足！');
                }

                $user->has_year_bonus -= $money;
                $user->save();

                break;
            case 3:
                $jixiao_wd_days = config('site.jixiao_wd_days');
                if ($jixiao_wd_days) {
                    $jixiao_wd_days_arr = explode(' - ', $jixiao_wd_days);
                    if (time() < strtotime($jixiao_wd_days_arr[0]) || time() > strtotime($jixiao_wd_days_arr[1])) {
                        $this->error('今日不可提现！');
                    }
                }
                $money = input('money');
                if (!$money || $money <= 0) {
                    $this->error('必须输入正确提现金额！');
                }

                if ($user->jixiao < $money) {
                    $this->error('余额不足！');
                }

                $user->jixiao -= $money;
                $user->save();

                break;
        }

        $orderNum = create_order($userId);
        $wdata = [
            'order_num' => $orderNum,
            'type' => $type,
            'user_id' => $userId,
            'money' => $money,
            'status' => 0,
        ];

        $res = Withdrawal::create($wdata);
        if (!$res) {
            $this->error('提现申请失败！');
        }

        $this->success('提现申请成功，等待后台审核！');
    }

    /**
     * 判断是否签到
     * @param $signConfig
     * @param $userId
     * @param $date
     * @return int
     */
    private function getNum($signConfig, $userId, $date)
    {
        $tnum = 0;
        $num1 = 0;
        foreach ($signConfig as $v1) {
            $start1 = strtotime($date . $v1[0]);
            $end1 = strtotime($date . $v1[1]);
            $where = [
                'user_id' => $userId,
                'createtime' => [['>=', $start1], ['<', $end1]]
            ];
            $sign = Sign::where($where)->find();

            if ($sign) {
                $num1 += 1;
            }

        }

        if ($num1 >= 2) {
            $tnum += 1;
        }

        return $tnum;
    }
}
